package com.nic.view.widget;

import android.content.Context;
import android.graphics.PointF;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.LinearSmoothScroller;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.animation.DecelerateInterpolator;

import java.lang.reflect.Field;

public class WrapContentLinearLayoutManager extends LinearLayoutManager {
    private float MILLISECONDS_PER_INCH = 50f;
    private Context context;

    public WrapContentLinearLayoutManager(Context context) {
        super(context);
        this.context = context;
//        setSpeedSlow();
    }

    public WrapContentLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
        super(context, orientation, reverseLayout);
        this.context = context;
        setSpeedSlow();
    }

    public WrapContentLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        this.context = context;
//        setSpeedSlow();
    }

    @Override
    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
        try {
            super.onLayoutChildren(recycler, state);
        } catch (IndexOutOfBoundsException e) {
            Log.e("problem", "meet a IOOBE in RecyclerView");
        }
    }

    @Override
    public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state,
                                       int position) {
        try {
            LinearSmoothScroller linearSmoothScroller = new LinearSmoothScroller(
                    recyclerView.getContext()) {
                @Override
                public PointF computeScrollVectorForPosition(int targetPosition) {
                    return WrapContentLinearLayoutManager.this
                            .computeScrollVectorForPosition(targetPosition);
                }

                // This returns the milliseconds it takes to
                // scroll one pixel.
                @Override
                protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
                    return MILLISECONDS_PER_INCH / displayMetrics.density;
                    // 返回滑动一个pixel需要多少毫秒
                }


                @Override
                protected void onTargetFound(View targetView, RecyclerView.State state,
                                             Action action) {
                    if (getLayoutManager() == null) {
                        return;
                    }
                    int dx = calculateDxToMakeVisible(targetView, getHorizontalSnapPreference());
                    int dy = calculateDyToMakeVisible(targetView, getVerticalSnapPreference());
                    if (dx > 0) {
                        dx = dx - getLayoutManager().getLeftDecorationWidth(targetView);
                    } else {
                        dx = dx + getLayoutManager().getRightDecorationWidth(targetView);
                    }
                    if (dy > 0) {
                        dy = dy - getLayoutManager().getTopDecorationHeight(targetView);
                    } else {
                        dy = dy + getLayoutManager().getBottomDecorationHeight(targetView);
                    }
                    final int distance = (int) Math.sqrt(dx * dx + dy * dy);
                    final int time = calculateTimeForDeceleration(distance);
                    if (time > 0) {// new AccelerateInterpolator()
                        action.update(-dx, -dy, time, new DecelerateInterpolator());
                    }
                }

            };
            linearSmoothScroller.setTargetPosition(position);
            startSmoothScroll(linearSmoothScroller);
        } catch (Exception e) {
            Log.e("problem", "meet a SmoothScroll in RecyclerView");
        }
    }

    public void setSpeedSlow() {
// 自己在这里用density去乘，希望不同分辨率设备上滑动速度相同
// 0.3f是自己估摸的一个值，可以根据不同需求自己修改
        MILLISECONDS_PER_INCH = context.getResources().getDisplayMetrics().density * 0.8f;
    }

    public void setSpeedFast() {
        MILLISECONDS_PER_INCH = context.getResources().getDisplayMetrics().density * 0.03f;
    }

    /**
     * 改变Recycler的滑动速度
     *
     * @param recyclerView //滑动速度默认是8000dp
     */
    public static void setMaxFlingVelocity(RecyclerView recyclerView) {
        try {
            Field field = recyclerView.getClass().getDeclaredField("mMaxFlingVelocity");
            field.setAccessible(true);
            int velocity = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2000, recyclerView.getResources().getDisplayMetrics());
            field.set(recyclerView, velocity);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
